import ajax from '@/assets/scripts/ajax'
import utils from '@/assets/scripts/utils'

function removeUnexpectedParams(connectionInfo) {
  const options = {
    ...connectionInfo
  }
  delete options.databases
  return options
}

const apis = {
  base: {
    securityKey() {
      return ajax.get('/api/v1/security/key')
    }
  },
  dbm: {
    connection: {
      test(connectionInfo) {
        connectionInfo = removeUnexpectedParams(connectionInfo)
        return ajax.put('/api/v1/connection', {
          options: connectionInfo
        })
      },
      getAll() {
        return ajax.get('/api/v1/connection')
      },
      set(connectionInfo) {
        connectionInfo = removeUnexpectedParams(connectionInfo)
        return ajax.post('/api/v1/connection', {
          options: connectionInfo
        })
      },
      connect(connectionInfo) {
        connectionInfo = removeUnexpectedParams(connectionInfo)
        return ajax.post('/api/v1/database/connect', {
          options: connectionInfo
        })
      },
      remove(connectionId) {
        return ajax.delete('/api/v1/connection', {
          id: connectionId
        })
      },
      execute(connectionInfo, database, args) {
        connectionInfo = removeUnexpectedParams(connectionInfo)
        const option = utils.getQueryParams(connectionInfo, {
          name: database
        }, args)
        return ajax.post('/api/v1/database/execute', option)
      }
    },
    database: {
      getInfo(connectionInfo, database) {
        connectionInfo = removeUnexpectedParams(connectionInfo)
        return ajax.post(
          '/api/v1/database/info',
          utils.getQueryParams(connectionInfo, {
            name: database
          })
        )
      }
    },
    table: {
      getDefinition(table) {
        return ajax.post('/api/v1/database/table/definition', utils.getQueryParams({
          table: table
        }))
      },
      getColumns(table) {
        return ajax.post('/api/v1/database/table/columns', utils.getQueryParams({
          table: table
        }))
      },
      export(tables) {
        return ajax.post('/api/v1/database/export', utils.getQueryParams({
          table: tables.join(',')
        })).then((data) => {
          const filename = data[0]
          window.open('/api/v1/database/export/download?filename=' + encodeURI(filename), '_self')
        })
      },
      exportDoc() {
        return ajax.post('/api/v1/database/exportDoc', utils.getQueryParams({})).then((data) => {
          const filename = data[0]
          window.open('/api/v1/database/export/download?filename=' + encodeURI(filename), '_self')
        })
      }
    }
  }
}

export default apis
